#!/usr/bin/env python

import os
import sys

basePath = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))

sys.path.append(os.path.join(basePath,'modules'))
import mods

sync = False



def Install():

	os.system("""dropdb %s""" % (mods.dbName))

	os.system("""createdb %s""" % (mods.dbName))


	sqlFileList = ['locations', 'location_todo', 'public_holidays', 'db_version', 'tickets', 'oid_associations', 'oid_nonces', 'user_log', 'users']

	if sync:
		for file in sqlFileList:
			sqlFile = '%s.sql' % (file)
			source = "http://opendb.co.za/download/pg/%s.sql" % (file)
			destination = os.path.join(basePath, 'setup', 'current', sqlFile)
			os.system("""wget -v %s -O %s""" % (source, destination))

	for file in sqlFileList:
		sqlFile = os.path.join(basePath, 'setup', 'current', '%s.sql' % (file))
		os.system("""psql -q %s < %s""" % (mods.dbName, sqlFile))



def Upgrade():
	pass
	#dbConnection = mods.GetDBConnection()
	#cursor = dbConnection.cursor()


	#dbConnection.commit()




if __name__ == "__main__":
	os.system("""sudo /etc/init.d/apache2 stop""")


	import optparse

	parser = optparse.OptionParser("usage: %prog [options]")
	parser.add_option("--sync", action="store_true", dest="sync", help="Sync data from OpenDB")

	(options, args) = parser.parse_args()

	if options.sync:
		sync = True



	if mods.production:
		Upgrade()
	else:
		Install()
		Upgrade()

	os.system("""sudo /etc/init.d/apache2 start""")


